package utils

import (
	"bufio"
	"fmt"
	"github.com/xuri/excelize/v2"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"
)

var filePath = "./data"

func SaveUploadfile2TmpFile(file multipart.File, handler *multipart.FileHeader) (string, error) {
	tmpFile, err := ioutil.TempFile("", handler.Filename)
	if err != nil {
		return "", err
	}
	defer func(tmpFile *os.File) {
		err := tmpFile.Close()
		if err != nil {

		}
	}(tmpFile)
	if _, err = io.Copy(tmpFile, file); err != nil {
		return "", err
	}
	return tmpFile.Name(), nil
}
func SaveUploadFileToLocalPath(file multipart.File, handler *multipart.FileHeader) (string, error) {
	pathExists, err2 := PathExists(filePath)
	if err2 != nil {
		return "", err2
	}
	if !pathExists { //not exists path ,will create path
		err := os.Mkdir(filePath, os.ModePerm)
		if err != nil {
			return "", err
		}
	}
	// add time flag to the file name
	nowTime := time.Now()
	nowTimeStr := nowTime.Format("2006-01-02 15:04:05")
	nowTimeStr = strings.Replace(nowTimeStr, "-", "", -1)
	nowTimeStr = strings.Replace(nowTimeStr, " ", "", -1)
	nowTimeStr = strings.Replace(nowTimeStr, ":", "", -1)
	localFileName := filePath + "/" + nowTimeStr + "_" + handler.Filename
	fileExists, err2 := PathExists(localFileName)
	if err2 != nil {
		return "", err2
	}
	if fileExists { // exists file should be removed ,because will conflict which the new upload file
		if err := os.Remove(localFileName); err != nil {
			return "", err
		}
	}
	out, err := os.Create(localFileName)
	if err != nil {
		return "", err
	}
	defer func(out *os.File) {
		err := out.Close()
		if err != nil {

		}
	}(out)
	_, err = io.Copy(out, file)
	if err != nil {
		return "", err
	}
	return localFileName, nil
}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

func ReadExcel(filename string) ([][]string, error) {
	ret := [][]string{}
	f, err := excelize.OpenFile(filename)
	if err != nil {
		fmt.Println("read excel error", err.Error())
		return ret, err
	}
	sheets := f.GetSheetMap()
	// fmt.Println(sheets)
	sheet0 := sheets[1]
	// fmt.Println("first one tab", sheet0)
	rows, err := f.GetRows(sheet0)
	if err != nil {
		return rows, err
	}
	return rows, nil
}

func DownloadFile(urlPath string) (string, error) {
	if contains := strings.Contains(urlPath, "http"); contains == false {
		urlPath = "http://" + urlPath
	}
	res, err := http.Get(urlPath)
	if err != nil {
		return "", err
	}
	reader := bufio.NewReaderSize(res.Body, 32*1024)
	pathExists, err2 := PathExists(filePath)
	if err2 != nil {
		return "", err
	}
	if !pathExists { //not exists path ,will create path
		err := os.Mkdir(filePath, os.ModePerm)
		if err != nil {
			return "", err
		}
	}
	base := filepath.Base(urlPath)
	localFileName := filePath + "/" + base
	fileExists, err2 := PathExists(localFileName)
	if err2 != nil {
		return "", err2
	}
	if fileExists { // exists file should be removed ,because will conflict which the new upload file
		if err := RemoveFile(localFileName); err != nil {
			return "", err
		}
	}
	out, err := os.Create(localFileName)
	if err != nil {
		return "", err
	}
	defer func(out *os.File) {
		err := out.Close()
		if err != nil {

		}
	}(out)
	_, err = io.Copy(out, reader)
	if err != nil {
		return "", err
	}
	return localFileName, nil
}

func RemoveFile(path string) error {
	if err := os.Remove(path); err != nil {
		return err
	}
	return nil
}
